/**
 * 使用统计模型
 * @module models/stats
 */

const sqlite3 = require('sqlite3').verbose();
const config = require('../config/config');

/**
 * 统计管理类，提供使用统计相关的数据库操作
 */
class Stats {
  /**
   * 记录工具使用
   * @param {number} userId - 用户ID
   * @param {string} toolType - 工具类型
   * @param {string} operationType - 操作类型
   * @param {Object} metadata - 元数据
   * @returns {Promise<Object>} 记录的使用统计
   */
  static async recordUsage(userId, toolType, operationType, metadata = {}) {
    return new Promise((resolve, reject) => {
      const db = new sqlite3.Database(config.dbPath);
      
      const usedAt = new Date().toISOString();
      const metadataStr = JSON.stringify(metadata);
      
      const stmt = db.prepare(`
        INSERT INTO usage_stats (user_id, tool_type, operation_type, metadata, used_at)
        VALUES (?, ?, ?, ?, ?)
      `);
      
      stmt.run(
        userId, 
        toolType, 
        operationType, 
        metadataStr, 
        usedAt, 
        function(err) {
          stmt.finalize();
          db.close();
          
          if (err) {
            return reject(err);
          }
          
          resolve({
            id: this.lastID,
            userId,
            toolType,
            operationType,
            metadata,
            usedAt
          });
        }
      );
    });
  }
  
  /**
   * 获取用户的使用统计
   * @param {number} userId - 用户ID
   * @param {string} timeRange - 时间范围（'today', 'week', 'month', 'all'）
   * @returns {Promise<Object>} 用户的使用统计
   */
  static async getUserStats(userId, timeRange = 'all') {
    return new Promise((resolve, reject) => {
      const db = new sqlite3.Database(config.dbPath);
      
      // 根据时间范围生成SQL条件
      let timeCondition = '';
      switch (timeRange) {
        case 'today':
          timeCondition = "AND date(used_at) = date('now')";
          break;
        case 'week':
          timeCondition = "AND date(used_at) BETWEEN date('now', '-7 days') AND date('now')";
          break;
        case 'month':
          timeCondition = "AND date(used_at) BETWEEN date('now', '-30 days') AND date('now')";
          break;
        default:
          timeCondition = '';
          break;
      }
      
      // 查询总使用次数
      db.get(
        `SELECT COUNT(*) as total FROM usage_stats 
         WHERE user_id = ? ${timeCondition}`,
        [userId],
        (err, totalResult) => {
          if (err) {
            db.close();
            return reject(err);
          }
          
          // 查询按工具类型分组的统计
          db.all(
            `SELECT tool_type, COUNT(*) as count 
             FROM usage_stats 
             WHERE user_id = ? ${timeCondition}
             GROUP BY tool_type`,
            [userId],
            (err, toolTypesResult) => {
              if (err) {
                db.close();
                return reject(err);
              }
              
              // 查询按操作类型分组的统计
              db.all(
                `SELECT operation_type, COUNT(*) as count 
                 FROM usage_stats 
                 WHERE user_id = ? ${timeCondition}
                 GROUP BY operation_type`,
                [userId],
                (err, operationTypesResult) => {
                  if (err) {
                    db.close();
                    return reject(err);
                  }
                  
                  // 查询最近的使用记录
                  db.all(
                    `SELECT * FROM usage_stats 
                     WHERE user_id = ? ${timeCondition}
                     ORDER BY used_at DESC
                     LIMIT 10`,
                    [userId],
                    (err, recentUsage) => {
                      db.close();
                      
                      if (err) {
                        return reject(err);
                      }
                      
                      // 格式化最近使用记录
                      const formattedRecentUsage = recentUsage.map(item => {
                        return {
                          id: item.id,
                          toolType: item.tool_type,
                          operationType: item.operation_type,
                          metadata: JSON.parse(item.metadata),
                          usedAt: item.used_at
                        };
                      });
                      
                      // 格式化工具类型统计
                      const toolTypes = {};
                      toolTypesResult.forEach(item => {
                        toolTypes[item.tool_type] = item.count;
                      });
                      
                      // 格式化操作类型统计
                      const operationTypes = {};
                      operationTypesResult.forEach(item => {
                        operationTypes[item.operation_type] = item.count;
                      });
                      
                      resolve({
                        timeRange,
                        total: totalResult.total,
                        toolTypes,
                        operationTypes,
                        recentUsage: formattedRecentUsage
                      });
                    }
                  );
                }
              );
            }
          );
        }
      );
    });
  }
  
  /**
   * 获取系统总体使用统计
   * @param {string} timeRange - 时间范围（'today', 'week', 'month', 'all'）
   * @returns {Promise<Object>} 系统使用统计
   */
  static async getSystemStats(timeRange = 'all') {
    return new Promise((resolve, reject) => {
      const db = new sqlite3.Database(config.dbPath);
      
      // 根据时间范围生成SQL条件
      let timeCondition = '';
      switch (timeRange) {
        case 'today':
          timeCondition = "WHERE date(used_at) = date('now')";
          break;
        case 'week':
          timeCondition = "WHERE date(used_at) BETWEEN date('now', '-7 days') AND date('now')";
          break;
        case 'month':
          timeCondition = "WHERE date(used_at) BETWEEN date('now', '-30 days') AND date('now')";
          break;
        default:
          timeCondition = '';
          break;
      }
      
      // 查询总使用次数
      db.get(
        `SELECT COUNT(*) as total FROM usage_stats ${timeCondition}`,
        [],
        (err, totalResult) => {
          if (err) {
            db.close();
            return reject(err);
          }
          
          // 查询活跃用户数
          db.get(
            `SELECT COUNT(DISTINCT user_id) as activeUsers FROM usage_stats ${timeCondition}`,
            [],
            (err, activeUsersResult) => {
              if (err) {
                db.close();
                return reject(err);
              }
              
              // 查询按工具类型分组的统计
              db.all(
                `SELECT tool_type, COUNT(*) as count 
                 FROM usage_stats 
                 ${timeCondition}
                 GROUP BY tool_type
                 ORDER BY count DESC`,
                [],
                (err, toolTypesResult) => {
                  if (err) {
                    db.close();
                    return reject(err);
                  }
                  
                  // 查询按操作类型分组的统计
                  db.all(
                    `SELECT operation_type, COUNT(*) as count 
                     FROM usage_stats 
                     ${timeCondition}
                     GROUP BY operation_type
                     ORDER BY count DESC`,
                    [],
                    (err, operationTypesResult) => {
                      if (err) {
                        db.close();
                        return reject(err);
                      }
                      
                      // 查询每日使用统计
                      db.all(
                        `SELECT date(used_at) as date, COUNT(*) as count 
                         FROM usage_stats 
                         ${timeCondition ? timeCondition + ' AND' : 'WHERE'} date(used_at) >= date('now', '-30 days')
                         GROUP BY date(used_at)
                         ORDER BY date(used_at)`,
                        [],
                        (err, dailyStats) => {
                          db.close();
                          
                          if (err) {
                            return reject(err);
                          }
                          
                          // 格式化工具类型统计
                          const toolTypes = {};
                          toolTypesResult.forEach(item => {
                            toolTypes[item.tool_type] = item.count;
                          });
                          
                          // 格式化操作类型统计
                          const operationTypes = {};
                          operationTypesResult.forEach(item => {
                            operationTypes[item.operation_type] = item.count;
                          });
                          
                          // 格式化每日统计
                          const dailyUsage = {};
                          dailyStats.forEach(item => {
                            dailyUsage[item.date] = item.count;
                          });
                          
                          resolve({
                            timeRange,
                            total: totalResult.total,
                            activeUsers: activeUsersResult.activeUsers,
                            toolTypes,
                            operationTypes,
                            dailyUsage
                          });
                        }
                      );
                    }
                  );
                }
              );
            }
          );
        }
      );
    });
  }
  
  /**
   * 获取每日活跃用户数统计
   * @param {number} days - 查询多少天的数据
   * @returns {Promise<Object>} 每日活跃用户数统计
   */
  static async getDailyActiveUsers(days = 30) {
    return new Promise((resolve, reject) => {
      const db = new sqlite3.Database(config.dbPath);
      
      db.all(
        `SELECT date(used_at) as date, COUNT(DISTINCT user_id) as count 
         FROM usage_stats 
         WHERE date(used_at) >= date('now', '-${days} days')
         GROUP BY date(used_at)
         ORDER BY date(used_at)`,
        [],
        (err, results) => {
          db.close();
          
          if (err) {
            return reject(err);
          }
          
          // 格式化每日活跃用户数
          const dailyActiveUsers = {};
          results.forEach(item => {
            dailyActiveUsers[item.date] = item.count;
          });
          
          resolve({
            dailyActiveUsers
          });
        }
      );
    });
  }
}

module.exports = Stats; 